package com.yenlien.traceyun.usercenter.service;

import com.yenlien.traceyun.usercenter.controller.form.GovConfigForm;
import com.yenlien.traceyun.usercenter.dao.CompanyCustomAppVersionDao;
import com.yenlien.traceyun.usercenter.dao.CompanyDao;
import com.yenlien.traceyun.usercenter.dao.GovConfigDao;
import com.yenlien.traceyun.usercenter.entity.Company;
import com.yenlien.traceyun.usercenter.entity.CompanyCustomAppVersion;
import com.yenlien.traceyun.usercenter.entity.GovConfig;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: bigwangy@sina.com
 * @create: 2021-02-19
 * @description:
 **/

@Service
public class GovConfigService {

    @Autowired
    private FileService fileService;

    @Autowired
    private GovConfigDao govConfigDao;

    @Autowired
    private CompanyCustomAppVersionDao companyCustomAppVersionDao;

    @Autowired
    private CompanyDao companyDao;

    @Transactional(rollbackFor = RuntimeException.class)
    public void setGovConfig(GovConfigForm form, List<MultipartFile> files) throws Exception {
        // 不能选择相同的产品
        List<CompanyCustomAppVersion> companyCustomAppVersions = form.getCompanyCustomAppVersions();
        if (companyCustomAppVersions != null && companyCustomAppVersions.size() > 0) {
            List<String> ids = companyCustomAppVersions.stream().map(CompanyCustomAppVersion::getCustomAppId).distinct().collect(Collectors.toList());
            if (ids.size() != companyCustomAppVersions.size()) {
                throw new BusinessException("不能选择相同产品");
            }
        }
        if (!StringUtils.isEmpty(form.getGovConfig().getId())) {
            GovConfig govConfig = null;
            govConfig = govConfigDao.findById(form.getGovConfig().getId()).get();
            fileService.upload(govConfig, form.getGovConfig(), files);
        } else {
            fileService.upload(null, form.getGovConfig(), files);
        }
        govConfigDao.save(form.getGovConfig());
        Company company = companyDao.findById(form.getGovConfig().getCompanyId());
        company.setExpiretime(form.getGovConfig().getExpiretimeStart());
        company.setExpiretimeEnd(form.getGovConfig().getExpiretimeEnd());
        companyDao.save(company);
        companyCustomAppVersionDao.deleteByCompanyId(company.getId());
        companyCustomAppVersionDao.saveAll(form.getCompanyCustomAppVersions());
    }
}
